package com.atliuzu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.flink.calcite.shaded.com.google.common.base.CaseFormat;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Administrator
 * @Time 2022-08-21-11:29
 */
public class JdbcUtil {
    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean underScoreToCamel) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //创建集合存放结果数据
        ArrayList<T> list = new ArrayList<>();

        PreparedStatement preparedStatement =null;
        ResultSet resultSet =null;

        try {
            //编译sql
            preparedStatement = connection.prepareStatement(sql);

            //执行sql
            resultSet = preparedStatement.executeQuery();


            //获取结果元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取列数
            int columnCount = metaData.getColumnCount();

            //行遍历
            while (resultSet.next()){
                //构建T对象
                T t = clz.newInstance();

                //列遍历
                for (int i = 0; i < columnCount; i++) {
                    String columnName = metaData.getColumnName(i + 1);//metadata下角标从1开始
                    Object value = resultSet.getObject(columnName);

                    //给T对象赋值
                    if (underScoreToCamel){
                        columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                    }

                    BeanUtils.setProperty(t,columnName,value);
                }
                //将数据写入list
                list.add(t);
            }
        } finally {

            if (resultSet!=null){
                resultSet.close();
            }
            if (preparedStatement!=null){
                preparedStatement.close();
            }
        }

        return list;

    }


    public static void main(String[] args) throws Exception {

        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();

        List<JSONObject> queryList = queryList(connection,
                "select * from EDU_REALTIME.DIM_COURSE_INFO",
                JSONObject.class,
                true);
        for (JSONObject jsonObject : queryList) {
            System.out.println(jsonObject);
        }



        connection.close();}
}
